package com.wfcm.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.wfcm.entity.*;
import com.wfcm.exception.WFCMException;
import com.wfcm.service.*;
import com.wfcm.utils.ISsoLoginHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wfcm.annotation.IgnoreToken;
import com.wfcm.utils.R;
import com.wfcm.utils.WebUtils;


/**
 * 
 * @content 购物车Controller
 */
@RequestMapping("/shoppingCart")
@Controller
public class ShoppingCarController {
	private Logger log = LoggerFactory.getLogger(AdInfoController.class);
	@Autowired
	WfCourseChapterService courseChapterService;
	@Autowired
	WfCourseInfoService courseInfoService;
	@Autowired
	private WfShoppingCartService shoppingCartService;
	@Autowired
	private WfGoodsOrderService goodsOrderService;
	@Autowired
	private WfGoodsOrderRelationService goodsOrderRelationService ;	
	@Autowired
	private WfVipCardService vipCardService;
	@Autowired
	private WfCollageOrderService collageOrderService;
	
	/**
	 * 购物车展示接口
	 */
	@RequestMapping("/goods")
	@ResponseBody
	public R goods(HttpServletRequest req) {
		Integer userId = ISsoLoginHelper.confirm(req);
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userId", userId);
		
		List<WfShoppingCartEntity> resultList = new ArrayList<WfShoppingCartEntity>();
		List <WfCourseInfoEntity> courseSpeakerList = new ArrayList<WfCourseInfoEntity>();
		List<WfShoppingCartEntity> shoppingCarList = shoppingCartService.queryList(map);
		for(int i=0 ; i<shoppingCarList.size(); i++) {
			if(1 == shoppingCarList.get(i).getType()) {//课程
				map.put("foreignId", shoppingCarList.get(i).getForeignid());
				List<WfShoppingCartEntity> courseList =	shoppingCartService.queryCourseList(map);
				resultList.add(courseList.get(0));
			}else if(2 == shoppingCarList.get(i).getType()) {//章节
				map.put("foreignId", shoppingCarList.get(i).getForeignid());
				List<WfShoppingCartEntity> chapterList =	shoppingCartService.queryChapterList(map);
				resultList.add(chapterList.get(0));
			}else if(3 == shoppingCarList.get(i).getType()) {//课程包
				map.put("foreignId", shoppingCarList.get(i).getForeignid());
				List<WfShoppingCartEntity> vipCardList =	shoppingCartService.queryVipCardList(map);
				for(int j=0; j<vipCardList.size(); j++) {
					List<WfCardCourseRelationEntity> cardCourseRelationList = vipCardList.get(j).getVipCardEntity().getCardCourseRelationList();
					Map<String,Object> csMap = new HashMap<String,Object>();
					for(int k=0; k<cardCourseRelationList.size(); k++) {
						csMap.put("courseId", cardCourseRelationList.get(k).getCourseid());
						courseSpeakerList = courseInfoService.queryList(csMap);//查出对应的讲师
						cardCourseRelationList.get(k).setCourseInfoEntity(courseSpeakerList.get(0));
					}
				}
				resultList.add(vipCardList.get(0));
			}
		}
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("resultList", resultList);
		
		return R.ok(resultMap);
	}	
	
	/**
	 * 删除购物车数据
	 */
	@RequestMapping("/delGoods")
	@ResponseBody
	public R delGoods(HttpServletRequest req) {
		Integer userId = ISsoLoginHelper.confirm(req);
	
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userId", userId);
		List<WfShoppingCartEntity> shoppingCarList = shoppingCartService.queryList(map);//查出本人的购物车列表
		
		String goodsId = req.getParameter("goodsId");
		String[] result = goodsId.split(",");
		
		for(int i=0; i<result.length; i++) {
			int id = Integer.parseInt(result[i]);
			for(int k=0; k<shoppingCarList.size(); k++) {//判断前台传来的购物车id 是否属于本人
				if(id == shoppingCarList.get(k).getId()) {
					shoppingCartService.delete(id);
				};
			}
		}
		return R.ok();
	}	
	
	/**
	 * 加入购物车
	 */
	@RequestMapping("/addGoods")
	@ResponseBody
	public R addGoods(HttpServletRequest req) {
		Integer userId = ISsoLoginHelper.confirm(req);
		//type商品类型（1.课程 2.章节3.vip卡4商品）
		String type = req.getParameter("type");
		String foreignId = req.getParameter("foreignId");//商品id
		String price = req.getParameter("price");
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userId", userId);
		map.put("type", type);
		map.put("foreignId", foreignId);
		List<WfShoppingCartEntity> shoppingCarList = shoppingCartService.queryList(map);
		if(shoppingCarList.size()>0) {
			return R.error(52,"您已经加入购物车了");
		}

		//判断是否已参加拼团
		Map collageMap = new HashMap<String ,Object>();
		collageMap.put("toUserId",userId);
		collageMap.put("foreignId",foreignId);
		collageMap.put("type",type);
		//获取状态status not in(1,4) 的最新订单
		WfCollageOrderEntity collage = collageOrderService.queryCollaging(collageMap);//获取团单状态；所买课程信息；参团最多人数；
		if(collage!=null){
			return R.error(85,"此课程您已参加拼团，请勿重复购买！");
		}

		int access = -1;
		String productName = null;
		if("1".equals(type)) {
			access = checkCourse(userId,Integer.valueOf(foreignId));
			if(access == 1) {
				return R.error(58,"此课程您已经购买！");
			}
			/*productName = checkContainCourse(userId,Integer.valueOf(foreignId));//判断课程中的某章节是否已购买
			if(productName != null) {
				return R.error(61,"此课程中的章节您已经购买！");
			}*/
		}else if("2".equals(type)){
			access = checkChapter(userId,Integer.valueOf(foreignId));
			if(access == 2) {
				return R.error(59,"此章节您已经购买！");
			}
		}else if("3".equals(type)){
			access = checkVipCard(userId,Integer.valueOf(foreignId));
			if(access == 3) {
				return R.error(60,"此课程包您已经购买！");
			}
			/*productName = checkContainVipCard(userId,Integer.valueOf(foreignId));
			if(productName != null) {
				return R.error(62,"此课程包中的课程您已经购买！");
			}*/
		}
		
		WfShoppingCartEntity shoppingCart = new WfShoppingCartEntity();
		shoppingCart.setUserid(userId);
		shoppingCart.setType(Integer.valueOf(type));
		shoppingCart.setForeignid(Integer.valueOf(foreignId));
		shoppingCart.setCreateTime(new Date());
		shoppingCart.setPrice(price);
		shoppingCart.setNumber(1);//默认为1
		shoppingCart.setSaleflag(0);//默认为0
		shoppingCartService.save(shoppingCart);
		
		return R.ok();
	}	
	
	/**
	 * 购物车总量
	 */
	@RequestMapping("/total")
	@ResponseBody
	public R total(HttpServletRequest req) {
		Integer userId = ISsoLoginHelper.confirm(req);
		//type商品类型（1.课程 2.章节3.vip卡4商品）
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userId", userId);
		int total = shoppingCartService.queryTotal(map);
		
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("total", total);
		
		return R.ok(resultMap);
	}	
	
	//课程查重 查课程包中是否有已买的课程
	public String checkContainVipCard(int uid, int cardId) {
		int access = -1;//标识
		//获取已购课程个数
		Map<String,Object> map =new  HashMap<String,Object>();
		map.put("cardId", cardId);
		List<WfVipCardEntity> vipCardList = vipCardService.queryCourseList(map);
		String coursename = null;
		for(int i=0; i<vipCardList.size(); i++) {
			int courseId = vipCardList.get(i).getCardCourseRelationList().get(0).getCourseid();
			access = checkCourse(uid, courseId);
			if(access>0) {
				coursename = vipCardList.get(access).getCardCourseRelationList().get(0).getCourseInfoEntity().getCoursename();
				break;
			}
		}
		return coursename;//返回重复课程的名称
	}
		
	
	//课程查重 查课程中是否已买的章节
	public String checkContainCourse(int uid, int courseId) {
		int access = -1;//标识
		//获取已购课程个数
		Map<String,Object> map =new  HashMap<String,Object>();
		WfCourseInfoEntity courseInfo = courseInfoService.queryObjectIgnoreStatus(courseId);
		map.put("courseId", courseId);
		List<WfCourseChapterEntity> chapterList = courseChapterService.queryList(map);
		String chaptername = null;
		for(int i=0; i<chapterList.size(); i++) {
			int chapterId = chapterList.get(i).getId();
			
			access = checkChapter(uid,chapterId);
			if(access>0) {
				chaptername = chapterList.get(access).getChaptername();
				break;
			}
		}
		
		return chaptername;//返回重复章节的名称
	}
	
	//access  -1,初始值；1，课程相同，2，章节相同， 3，课程包相同
	//课程查重
	public int checkCourse(int uid, int courseId) {
		int access = -1;//标识
		//获取已购课程个数
		Map<String,Object> map =new  HashMap<String,Object>();
		map.put("uid", uid);
		map.put("orderStatus", 4);//订单状态（1.待付款2.待收货3.待评价4.已完成5.取消订单）
		List<WfGoodsOrderEntity>  goodsOrderList = goodsOrderService.queryList(map);//根据uid获取订单
		for(int i=0 ; i<goodsOrderList.size(); i++) {
			WfGoodsOrderEntity goodsOrderEntity = goodsOrderList.get(i);
			Map<String,Object> map2 =new  HashMap<String,Object>();
			map2.put("orderCode",goodsOrderEntity.getOrdercode());
			map2.put("goodsSort",1);//1.课程 2.章节3.vip卡 4商品
			List<WfGoodsOrderRelationEntity> courseList =  goodsOrderRelationService.queryList(map2);//根据订单号获取其中的课程
			for(int j=0 ; j<courseList.size(); j++) {
				if(courseId == courseList.get(j).getGoodsid()) {
					access = 1;
					break;//跳出课程循环
				}
			}
			if(access == 1) {
				break;//跳出订单循环
			}
			map2.put("goodsSort",3);//1.课程 2.章节3.vip卡 4商品
			List<WfGoodsOrderRelationEntity> vipList =  goodsOrderRelationService.queryList(map2);//根据订单号获取其中的课程包
			for(int m=0 ; m<vipList.size(); m++) {
				Integer vcId = vipList.get(m).getGoodsid();
				Map<String,Object> map3 =new  HashMap<String,Object>();
				map3.put("vipCardId",vcId);
				List<WfVipCardEntity> vipCardList = vipCardService.queryCourseList(map3);//获取课程包中个课程
				for(int k=0; k<vipCardList.size(); k++) {
					if(courseId == vipCardList.get(k).getCardCourseRelationList().get(0).getCourseInfoEntity().getId()) {
						access = 1;
						break;//若课程已买，则跳出课程包循环
					}
				}
			}
			if(access == 1) {
				break;//跳出订单循环
			}
		}
		return access;//若access为-1,则说明此课程没买过；为1，则说明课程已买过
	}
	
	//章节查重
	public  int checkChapter(int uid, int chapterId) {
		
		WfCourseChapterEntity courseChapter =  courseChapterService.queryObjectIgnoreStatus(chapterId);//获取当前课程
		int courseId = courseChapter.getCourseid();//章节所属的课程ID
		
		int access = -1;//标识
		//获取已购课程个数
		Map<String,Object> map1 =new  HashMap<String,Object>();
		map1.put("uid", uid);
		map1.put("orderStatus", 4);//订单状态（1.待付款2.待收货3.待评价4.已完成5.取消订单）
		List<WfGoodsOrderEntity>  goodsOrderList = goodsOrderService.queryList(map1);//根据uid获取订单
		for(int i=0 ; i<goodsOrderList.size(); i++) {
			WfGoodsOrderEntity goodsOrderEntity = goodsOrderList.get(i);
			Map<String,Object> map2 =new  HashMap<String,Object>();
			map2.put("orderCode",goodsOrderEntity.getOrdercode());
			map2.put("goodsSort",1);//1.课程 2.章节3.vip卡 4商品
			List<WfGoodsOrderRelationEntity> courseList =  goodsOrderRelationService.queryList(map2);//根据订单号获取其中的课程
			for(int j=0 ; j<courseList.size(); j++) {
				if(courseId == courseList.get(j).getGoodsid()) {
					access = 2;
					break;//跳出课程循环
				}
			}
			if(access == 2) {
				break;//跳出订单循环
			}
			map2.put("goodsSort",3);//1.课程 2.章节3.vip卡 4商品
			List<WfGoodsOrderRelationEntity> vipList =  goodsOrderRelationService.queryList(map2);//根据订单号获取其中的课程包
			for(int m=0 ; m<vipList.size(); m++) {
				Integer vcId = vipList.get(m).getGoodsid();
				Map<String,Object> map3 =new  HashMap<String,Object>();
				map3.put("vipCardId",vcId);
				List<WfVipCardEntity> vipCardList = vipCardService.queryCourseList(map3);//获取课程包中个课程
				for(int k=0; k<vipCardList.size(); k++) {
					if(courseId == vipCardList.get(k).getCardCourseRelationList().get(0).getCourseInfoEntity().getId()) {
						access = 2;
						break;//若课程已买，则跳出课程包循环
					}
				}
			}
			if(access == 2) {
				break;//跳出订单循环
			}
			map2.put("goodsSort",2);//1.课程 2.章节3.vip卡 4商品
			List<WfGoodsOrderRelationEntity> chapterList1 =  goodsOrderRelationService.queryList(map2);//根据订单号获取其中的章节
			for(int j=0 ; j<chapterList1.size(); j++) {
				if(chapterId == chapterList1.get(j).getGoodsid()) {
					access = 2;
				}
			}
		}
		return access;
	}
		
	//课程包查重
	public int checkVipCard(int uid, int vipCardId) {
		int access = -1;//标识
		//获取已购课程个数
		Map<String,Object> map1 =new  HashMap<String,Object>();
		map1.put("uid", uid);
		map1.put("orderStatus", 4);//订单状态（1.待付款2.待收货3.待评价4.已完成5.取消订单）
		List<WfGoodsOrderEntity>  goodsOrderList = goodsOrderService.queryList(map1);//根据uid获取订单
		for(int i=0 ; i<goodsOrderList.size(); i++) {
			WfGoodsOrderEntity goodsOrderEntity = goodsOrderList.get(i);
			Map<String,Object> map2 =new  HashMap<String,Object>();
			map2.put("orderCode",goodsOrderEntity.getOrdercode());
			map2.put("goodsSort",3);//1.课程 2.章节3.vip卡 4商品
			map2.put("vipCardId",vipCardId);//
			List<WfGoodsOrderRelationEntity> vipList =  goodsOrderRelationService.queryList(map2);//根据订单号获取其中的课程包
			if(vipList.size()>1) {
				access = 3;
				break;//若课程包已买，则跳出课程包循环
			}
		}
		return access;
	}


	/**
	 * 加入购物车  测试事务
	 */
	@RequestMapping("/saveAndGive")
	@ResponseBody
	public R saveAndGive(HttpServletRequest req) throws WFCMException{
		Integer userId = ISsoLoginHelper.confirm(req);
		//type商品类型（1.课程 2.章节3.vip卡4商品）
		String type = req.getParameter("type");
		String foreignId = req.getParameter("foreignId");//商品id
		String price = req.getParameter("price");

		try {
			shoppingCartService.saveAndGive(userId, Integer.valueOf(type), Integer.valueOf(foreignId), price);
		}catch (WFCMException re){
			throw  re;
		}
		return R.ok();
	}
}
